package com.hb.unic.core.async.impl;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.util.CollectionUtils;

import com.hb.unic.core.async.IMessageChannel;
import com.hb.unic.core.async.IMessageProcessor;
import com.hb.unic.core.context.Application;
import com.hb.unic.core.log.UnicLogger;
import com.hb.unic.core.log.UnicLoggerFactory;

/**
 * 线程池管道
 *
 * @since v1.0，2023/8/29 19:44，create by Mr.Huang.
 */
public class DefaultThreadChannel implements IMessageChannel {

    /**
     * log
     */
    private static final UnicLogger LOGGER = UnicLoggerFactory.getLogger(DefaultThreadChannel.class);

    /**
     * 线程池
     */
    private ThreadPoolExecutor executor;

    public DefaultThreadChannel(String threadPoolBeanName) {
        this.executor = Application.getContext().getBean(threadPoolBeanName, ThreadPoolExecutor.class);
    }

    @Override
    public void submit(AsyncMessage asyncMessage) {
        String messageType = asyncMessage.getMessageType();
        List<IMessageProcessor> processors = MessageConfigManager.getProcessors(messageType);
        if (CollectionUtils.isEmpty(processors)) {
            LOGGER.warn("Can not get message processor for type: {}", messageType);
            return;
        }
        for (IMessageProcessor processor : processors) {
            executor.execute(() -> processor.process(asyncMessage));
            LOGGER.info("Processor[] execute complete");
        }
    }
}
